package cn.yh.register.hosp.receiver;

import cn.yh.register.common.constant.MqConst;
import cn.yh.register.common.service.RabbitService;
import cn.yh.register.hosp.service.ScheduleService;
import cn.yh.register.model.hosp.Schedule;
import cn.yh.register.vo.msm.MsmVo;
import cn.yh.register.vo.order.OrderMqVo;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class HospiatalReceiver {

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_ORDER),
            value = @Queue(name = MqConst.QUEUE_ORDER, durable = "true"),
            key = MqConst.ROUTING_ORDER)
    )

    public void receive(Message message, Channel channel, OrderMqVo orderMqVo) {
        log.info("【医院服务-更新号源】：{}", JSONObject.toJSONString(orderMqVo));
        // 剩余预约数
        Integer availableNumber = orderMqVo.getAvailableNumber();
        Schedule schedule = null;
        // 判断是下单时的更新号源还是取消预约的更新号源
        if (availableNumber != null) {
            //下单时候更新号源
            // 排班id
            String scheduleId = orderMqVo.getScheduleId();
            // 可预约数
            Integer reservedNumber = orderMqVo.getReservedNumber();
            // 查询排班
            schedule = scheduleService.getById(scheduleId);

            schedule.setReservedNumber(reservedNumber);

        } else {
            // 取消预约的更新号源
            // 医院系统的排班主键
            String hosScheduleId = orderMqVo.getScheduleId();

            schedule = scheduleService.getByHosScheduleId(hosScheduleId);

            availableNumber = schedule.getAvailableNumber() + 1;
        }

        // 更新号源
        schedule.setAvailableNumber(availableNumber);

        scheduleService.updateSchedule(schedule);

        // 发送消息由短信服务消费
        MsmVo msmVo = orderMqVo.getMsmVo();
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        log.info("【医院服务-发送通知消息】：{}", JSONObject.toJSONString(msmVo));

    }

}
